package cn.tit.ias.controller.pc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.management.relation.Role;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.ObjectUtils.Null;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tit.ias.aop.MethodLog;
import cn.tit.ias.entity.CollegeInfo;
import cn.tit.ias.entity.DepartInfo;
import cn.tit.ias.entity.StoreInfo;
import cn.tit.ias.entity.UserInfo;
import cn.tit.ias.service.CollegeInfoService;
import cn.tit.ias.service.DepartInfoService;
import cn.tit.ias.service.DicUserRoleInfoService;
import cn.tit.ias.service.StoreInfoService;
import cn.tit.ias.util.controllerresponse.ControllerResponse;
import cn.tit.ias.util.controllerresponse.ControllerResponseFactory;

@Controller
@RequestMapping("/PCStoreHandler")
public class PCStoreInfoController {
	public static final String SUPER_ADMIN_ROLE = "超级管理员";
	@Autowired
	DepartInfoService departInfoService;
	
	@Autowired
	StoreInfoService storeInfoService;
	
	@Autowired
	DicUserRoleInfoService roleInfoService;
	
	@Autowired
	CollegeInfoService collegeService;
	/**获取登陆者学校的所有部门名称*/
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "listDepartName",method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> listDepartName(@RequestParam("college")String college){
		ControllerResponse response = ControllerResponseFactory.newInstance();
		
		// 通过shiro获取当前登录的对象
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		
		// 获取session域中当前登陆用户
	    UserInfo loginUser = (UserInfo) session.getAttribute("loginUser");
		// 获取当前用户的角色
	    String roleName = (String) session.getAttribute("loginUserRole");
		Integer collegeNum = null;
		String departNum = null;
		List<DepartInfo> listdeparts=new ArrayList<DepartInfo>();
		List<String> departnames=new ArrayList<String>();
		// 查询部门的条件
		DepartInfo condition = new DepartInfo();
		
		
		// 超级管理员获取
	    if(roleName.equals(SUPER_ADMIN_ROLE)) {
	    	if(college.equals("")){
	    		response.setResponseResult(ControllerResponse.RESPONSE_RESULT_SUCCESS);
	    		response.setResponseData(departnames);
	    		return response.generateResponse();
	    	}
	    	try {
	    		collegeNum = collegeService.getCollegeByName(college).getCollegeNum();
			} catch (Exception e) {
				response.setResponseResult(ControllerResponse.RESPONSE_RESULT_ERROR);
				response.setResponseMsg("该学校不存在");
				return response.generateResponse();
			}
	    }else{
	    	//普通管理员获取
	    	departNum = loginUser.getDepartNum();
	    	try {
	    		collegeNum = departInfoService.getObject(departNum).getCollegeNum();
			} catch (Exception e) {
				response.setResponseResult(ControllerResponse.RESPONSE_RESULT_ERROR);
				response.setResponseMsg("该学校不存在");
				return response.generateResponse();
			}
	    	
	    }
	    condition.setCollegeNum(collegeNum);
	    // 查询满足条件的部门
		listdeparts=(List<DepartInfo>) departInfoService.listDepartObjByCondition(condition).get("data");
		// 获取部门名称集合
		if(roleName.equals(SUPER_ADMIN_ROLE)){
			for(int i=0;i<listdeparts.size();i++)
			{
				departnames.add(listdeparts.get(i).getDepartName());
			}
		}else{
			String name = departInfoService.getObject(departNum).getDepartName();
			departnames.add(name);
		}
		
		response.setResponseData(departnames);
		return response.generateResponse();
	}
	/**
	 * 
	 * @Title: listObject @Description: 分页查询部门 @param: @param
	 *         collegeName @return: Map<String,Object> @throws
	 */
	@RequestMapping(value = "listStore", method = RequestMethod.GET)
	@ResponseBody
	//@MethodLog(name = "存放地管理模块",option = "查看存放地信息")
	public Map<String, Object> listStore(@Param("offset") int offset, @Param("limit") int limit,
			HttpServletRequest request, @Param("departName") String departName) {

		// 初始化response
		ControllerResponse response = ControllerResponseFactory.newInstance();

		// 获取查询的部门
		int total = 0;
		List<Map<String, Object>> listResult = new ArrayList<>();
		StoreInfo condition = new StoreInfo();
		String departNum="";
		try {
			departNum = departInfoService.getDepartByName(departName).getDepartNum();
		}catch(Exception e)
		{
			departNum = "";
		}
		if(departNum.equals("")) {
			/*空操作*/
		}else {
			condition.setDepartNum(departNum);
			// 查询结果
			Map<String, Object> queryRsult = storeInfoService.listStoreObjByConditionPage(offset, limit, condition);
			@SuppressWarnings("unchecked")
			List<StoreInfo> listStore = (List<StoreInfo>) queryRsult.get("data");
			total = (int) queryRsult.get("total");
			for (StoreInfo storeInfo : listStore) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("storeNum", storeInfo.getStoreNum());
				map.put("storeName", storeInfo.getStoreName());
				map.put("departName", departName);
				map.put("storeDoorNum", storeInfo.getStoreDoorNum());
				listResult.add(map);
			}
			response.setResponseResult(ControllerResponse.RESPONSE_RESULT_SUCCESS);
			response.setObjectInfo("rows", listResult);
		}
		response.setResponseTotal(total);
		return response.generateResponse();
	}
	
	/**
	 * 
	 * @Title: listStore_v1   
	 * @Description: 根据部门获取存放地，下拉框数据源  
	 * @param: @param offset
	 * @param: @param limit
	 * @param: @param request
	 * @param: @param departName
	 * @param: @return      
	 * @return: Map<String,Object>      
	 * @throws
	 */
	@RequestMapping(value = "listStore_v1", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> listStore_v1( @Param("departNum") String departNum) {
		// 初始化response
		ControllerResponse response = ControllerResponseFactory.newInstance();

		// 判断部门编号时候为空
		if(departNum.equals("")) {
			response.setResponseResult(ControllerResponse.RESPONSE_RESULT_ERROR);
			response.setResponseData(null);
		}else {
			StoreInfo condition = new StoreInfo();
			condition.setDepartNum(departNum);
			// 查询结果
			Map<String, Object> queryRsult = storeInfoService.listStoreObjByCondition(condition);
			response.setResponseResult(ControllerResponse.RESPONSE_RESULT_SUCCESS);
			response.setResponseData(queryRsult.get("data"));
		}
		return response.generateResponse();
	}
	
	/**修改存放地*/
	@RequestMapping(value="updatestore",method=RequestMethod.POST)
	@ResponseBody
	@MethodLog(name = "存放地管理模块",option = "修改存放地信息")
	public Map<String,Object> updatestore(@RequestBody Map<String,Object> store)
	{
		ControllerResponse response = ControllerResponseFactory.newInstance();
		String result = ControllerResponse.RESPONSE_RESULT_ERROR;
		int StoreNum=-1;
		String storeName="";
		String departName="";
		String doorName="";
		try {
			StoreNum=Integer.parseInt((String) store.get("storenum"));
			storeName=store.get("storename").toString();
			departName=(String) store.get("departname").toString();
			doorName=(String) store.get("storedoorname").toString();
		}catch(Exception e)
		{
			StoreNum=-1;
		}
		if(StoreNum!=-1)
		{
			try {
				/*修改成功*/
				StoreInfo storeinfo=new StoreInfo();
				storeinfo.setStoreNum(StoreNum);
				storeinfo.setStoreName(storeName);
				storeinfo.setStoreDoorNum(doorName);
				try {
					String departNum=departInfoService.getDepartByName(departName).getDepartNum();
					storeinfo.setDepartNum(departNum);
				}catch(Exception e) {
					/*部门名称获取部门编号失败*/
				}
				storeInfoService.updateObject(storeinfo);
				result = ControllerResponse.RESPONSE_RESULT_SUCCESS;
			}catch(Exception e) {
				/*修改失败*/
				result = ControllerResponse.RESPONSE_RESULT_ERROR;
			}
		}else {
			/*前端传来的数据发生错误*/
			result = ControllerResponse.RESPONSE_RESULT_ERROR;
		}
		response.setResponseResult(result);
		return response.generateResponse();
	}
	
	/**添加存放地*/
	@RequestMapping(value = "addStore",method = RequestMethod.POST)
	@ResponseBody
	@MethodLog(name = "存放地管理模块",option = "添加存放地信息")
	public Map<String,Object> addStore(@RequestBody Map<String,Object> message){
		ControllerResponse response = ControllerResponseFactory.newInstance();
		String StoreName="";
		String DepartNum="";
		String DoorName="";
		String result = ControllerResponse.RESPONSE_RESULT_ERROR;
		/*获取前端传来的信息*/
		try {
			StoreName=message.get("storename").toString();
			DepartNum=departInfoService.getDepartByName(message.get("storedepart").toString()).getDepartNum();
			DoorName = (String) message.get("doorname");
		}catch(Exception e) {
			DepartNum="";
		}
		if(!DepartNum.equals(""))
		{
			/*验证存放地*/
			StoreInfo condition = new StoreInfo();
			condition.setStoreName(StoreName);;
			if ((int)storeInfoService.listStoreObjByCondition(condition).get("total") != 0) {
				response.setResponseResult(ControllerResponse.RESPONSE_RESULT_ERROR);
				response.setResponseMsg("该名字已存在");
			} else  {
				//添加存放地
				StoreInfo Store=new StoreInfo();
				Store.setStoreName(StoreName);
				Store.setDepartNum(DepartNum);
				Store.setStoreDoorNum(DoorName);
				storeInfoService.addObject(Store);
				result = ControllerResponse.RESPONSE_RESULT_SUCCESS;
			}
		}else{
			/*部门获取错误-添加失败*/
			result = ControllerResponse.RESPONSE_RESULT_ERROR;
		}
		response.setResponseResult(result);
		return response.generateResponse();
	}
	
	@RequestMapping(value = "deleteStore",method = RequestMethod.GET)
	@ResponseBody
	@MethodLog(name = "存放地管理模块",option = "删除存放地信息")
	public Map<String,Object> deleteStore(@RequestParam("selectstoreNum")int StoreNum) {
		ControllerResponse response = ControllerResponseFactory.newInstance();
		System.out.println(StoreNum);
		// 要删除的部门编号
		int storenum=storeInfoService.getObject(StoreNum).getStoreNum();
		// 删除结果
		int result = -1;
		try{
			result=storeInfoService.deleteObject(storenum);
		}catch(Exception e)
		{
			result=-1;
		}
		if(result == -1) {
			response.setResponseResult(ControllerResponse.RESPONSE_RESULT_ERROR);
			response.setResponseMsg("删除失败");
		}else{
			System.out.println("删除成功");
			response.setResponseResult(ControllerResponse.RESPONSE_RESULT_SUCCESS);
			response.setResponseMsg("删除成功");
		}
		return response.generateResponse();
	}
	
}
